# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 10:37:47 2018

@author: jiujiujiu

链条

"""
from WriteData import writedata
from Tk import genearteMD5
import requests
import json
import time
from cs import day


def get_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_Zxun(url, data):
    text = get_html_text(url, data)
    if not text:
        return None
    text = json.loads(text)
    data = text['data']['list']
    dates = [time.strftime("%Y-%m-%d %X", time.localtime(int(date['create_time'])))[:10] for date in data]
    return dates


def get_dates_Kxun(url, data):
    text = get_html_text(url, data)
    if not text:
        return None
    text = json.loads(text)
    data = text['data']['list']
    dates = [time.strftime("%Y-%m-%d %X", time.localtime(date['create_time']))[:10] for date in data]
    for date in data:
        id = date['create_time']
    return (dates, id)


def count_process_one():  # 快讯

    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    id = '1746434226'
    while 1:
        data = {
            'id': '3type: 11',
            'time': id
        }
        url = 'http://www.liantiao.com/express/getMoreExpressList'
        dates = get_dates_Kxun(url, data)
        if not dates:
            break
        id = dates[1]
        print('----链条快讯获取中----')
        for date in dates[0]:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_two():  # 头条
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        data = {
            'id': '32',
            'page': a
        }
        url = 'http://www.liantiao.com/news/getColumnArticleList'
        dates = get_dates_Zxun(url, data)
        if not dates:
            break
        print('----链条资讯获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '链条'
    t1 = count_process_one()
    t2 = count_process_two()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
